package com.example.mapexport;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.maps2d.AMapUtils;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItemV2;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.poisearch.PoiResultV2;
import com.amap.api.services.poisearch.PoiSearchV2;
import com.chad.library.adapter4.BaseQuickAdapter;
import com.example.mapexport.activity.MapActivity;
import com.example.mapexport.adapter.PoiAdapter;
import com.example.mapexport.realm.CitySearchResult;
import com.example.mapexport.realm.MyPhoto;
import com.example.mapexport.realm.MyPoiItem;
import com.example.mapexport.realm.PoiSearchResult;
import com.example.mapexport.utils.MapUtils;
import com.example.mapexport.utils.RealmUtils;
import com.example.mapexport.utils.Utils;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import io.realm.RealmResults;

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private Button btnMap,btnSearch;
    private PoiAdapter poiAdapter;
    private EditText edPageNum;
    private EditText edCity;
    private EditText edKeyword;
    private TextView tvTotal,tvTotalPage;
    private List<MyPoiItem> dataList;
    int pageNum = 1;
    double lat;
    double lng;

    static final String SP_USERINFO = "userinfo";

    private RealmResults<PoiSearchResult> cityResults;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        recyclerView = findViewById(R.id.recyclerView);
        edPageNum = findViewById(R.id.edPageNum);
        btnMap = findViewById(R.id.btnMap);
        edCity = findViewById(R.id.edCity);
        edKeyword = findViewById(R.id.edKeyword);
        btnSearch = findViewById(R.id.btnSearch);
        tvTotal = findViewById(R.id.tvTotal);
        tvTotalPage = findViewById(R.id.tvTotalPage);

        btnMap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, MapActivity.class);
                startActivity(intent);
            }
        });

        SharedPreferences sharedPreferences = getSharedPreferences(SP_USERINFO,MODE_PRIVATE);
        pageNum = sharedPreferences.getInt("pageNum",1);
        edPageNum.setText(pageNum + "");

        String city = sharedPreferences.getString("city","昆山市");
        edCity.setText(city);

        String keyword = sharedPreferences.getString("keyword","广告");
        edKeyword.setText(keyword);
        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String city = edCity.getText().toString();
                if(TextUtils.isEmpty(city)){
                    return;
                }
                String keyword = edKeyword.getText().toString();
                if(TextUtils.isEmpty(keyword)){
                    return;
                }
                String pageNumStr = edPageNum.getText().toString();
                if(TextUtils.isEmpty(pageNumStr)){
                    return;
                }

                pageNum = Integer.parseInt(pageNumStr);
                SharedPreferences sharedPreferences = getSharedPreferences(SP_USERINFO,MODE_PRIVATE);
                SharedPreferences.Editor edit = sharedPreferences.edit();
                edit.putInt("pageNum",pageNum);
                edit.putString("city",city);
                edit.putString("keyword",keyword);
                edit.apply();
                locationKeyword(false);
            }
        });


        poiAdapter = new PoiAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        dataList = new ArrayList<>();
        poiAdapter.setItems(dataList);
        recyclerView.setAdapter(poiAdapter);
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this,DividerItemDecoration.VERTICAL);
        recyclerView.addItemDecoration(dividerItemDecoration);
//        locationKeyword(true);
    }

    private void locationKeyword(boolean cache) { // 先定位关键词经纬度，再进行多边形查询
        String city = edCity.getText().toString();
        if(TextUtils.isEmpty(city)) {
            return;
        }
        String keyword = edKeyword.getText().toString();
        if(TextUtils.isEmpty(keyword)){
            return;
        }
        CitySearchResult citySearchResult = RealmUtils.getInstance().getCityLocalData(city);
        if(null != citySearchResult) {
            Log.e("经纬度","查询到本地存在相同节点数据");
            lat = citySearchResult.getLat();
            lng = citySearchResult.getLng();
            Log.d("Geocode", "经度: " + lng + ", 纬度: " + lat);
            searchPoiRectangle();
        } else {
            if(cache) {
                return;
            }
            AMapLocationClient.updatePrivacyShow(this, true, true);
            AMapLocationClient.updatePrivacyAgree(this, true);
            try {
                GeocodeSearch geocoderSearch = new GeocodeSearch(this);
                geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
                    @Override
                    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
                    }

                    @Override
                    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
                        Gson gson = new Gson();
                        Log.e("" + i,gson.toJson(geocodeResult));
                        if (i == 1000) { // 成功码
                            lat = geocodeResult.getGeocodeAddressList().get(0).getLatLonPoint().getLatitude();
                            lng = geocodeResult.getGeocodeAddressList().get(0).getLatLonPoint().getLongitude();
                            Log.d("Geocode", "经度: " + lng + ", 纬度: " + lat);
                            RealmUtils.getInstance().saveCityLocalData(city,lat,lng);
                            searchPoiRectangle();
                        }
                    }
                });
                GeocodeQuery query = new GeocodeQuery(city, ""); // 城市名+空区域
                geocoderSearch.getFromLocationNameAsyn(query);
            } catch (AMapException e) {
                throw new RuntimeException(e);
            }
        }
    }

    int pollPageNum = 1;
    int pollAreaIndex = 0;
    List<List<LatLng>> fourArea;
    private void searchPoiRectangle() { // 多边形搜索，矩形搜索
        String keyword = edKeyword.getText().toString();
        if(TextUtils.isEmpty(edKeyword.getText().toString())){
            return;
        }
        String city = edCity.getText().toString();
        if(TextUtils.isEmpty(edCity.getText().toString())){
            return;
        }
        pollPageNum = 1;
        pollAreaIndex = 0;
        AMapLocationClient.updatePrivacyShow(this, true, true);
        AMapLocationClient.updatePrivacyAgree(this, true);
        fourArea = MapUtils.getInstance().pointsCreate4Cutting(lat,lng);

//        query - 查询字符串，多个关键字用“|”分割 。
//        ctgr - POI 类型的组合，比如定义如下组合：餐馆|电影院|景点 （POI类型请在网站“相关下载”处获取）。
//        city - 待查询城市（地区）的城市编码 citycode、城市名称（中文或中文全拼）、行政区划代码adcode。必设参数。
        PoiSearchV2.Query query = new PoiSearchV2.Query(keyword,"",null);
        query.setPageNum(pollPageNum);
        PoiSearchV2.ShowFields ShowFields = new PoiSearchV2.ShowFields(PoiSearchV2.ShowFields.BUSINESS|PoiSearchV2.ShowFields.PHOTOS);
        query.setShowFields(ShowFields);

        PoiSearchV2.SearchBound searchBound = new PoiSearchV2.SearchBound(MapUtils.getInstance().LatLngToPoint(fourArea.get(pollAreaIndex)));
        PoiSearchResult poiSearchResult = RealmUtils.getInstance().getPoiLocalData(query,searchBound);
        if(null != poiSearchResult) {
            Log.e("poi","查询到本地存在相同节点数据");
            Log.e("poi","导出本城市所有站点数据");
            cityResults = RealmUtils.getInstance().getCityAllPoiData(city,query);
            initList();
        } else {
            pollSearch();
        }
    }

    private void pollSearch() {
        Utils.showLoading(MainActivity.this);
        String keyword = edKeyword.getText().toString();
        if(TextUtils.isEmpty(edKeyword.getText().toString())){
            return;
        }
        String city = edCity.getText().toString();
        if(TextUtils.isEmpty(edCity.getText().toString())){
            return;
        }
        try {
            PoiSearchV2.Query query = new PoiSearchV2.Query(keyword,"",null);
            query.setPageNum(pollPageNum);
            PoiSearchV2.ShowFields ShowFields = new PoiSearchV2.ShowFields(PoiSearchV2.ShowFields.BUSINESS|PoiSearchV2.ShowFields.PHOTOS);
            query.setShowFields(ShowFields);

            PoiSearchV2.SearchBound searchBound = new PoiSearchV2.SearchBound(MapUtils.getInstance().LatLngToPoint(fourArea.get(pollAreaIndex)));

            PoiSearchV2 poiSearchV2 = new PoiSearchV2(this,query);
            poiSearchV2.setBound(searchBound); //设置多边形区域
//            Log.e("本次轮询pollPageNum","" + pollPageNum);
//            Log.e("本次轮询pollAreaIndex","" + pollAreaIndex);
            poiSearchV2.setOnPoiSearchListener(new PoiSearchV2.OnPoiSearchListener() {
                @Override
                public void onPoiSearched(PoiResultV2 poiResultV2, int code) {
                    if(null != poiResultV2) {
                        if(!poiResultV2.getPois().isEmpty()) {
                            RealmUtils.getInstance().savePoiLocalData(query,city,searchBound,poiResultV2);
                        }
                    }

                    Timer timer = new Timer();
                    timer.schedule(new TimerTask() { // 每秒最多3次查询，所以0.5秒查询一次
                        @Override
                        public void run() {
                            if(pollPageNum < 10) { // 10为最大页数
                                pollPageNum++;
                                pollSearch();
                            } else {
                                if(pollAreaIndex < fourArea.size() - 1){
                                    pollPageNum = 1;
                                    pollAreaIndex++;
                                    pollSearch();
                                } else {
                                    Utils.hideLoading();
                                    Log.e("轮询结束","1111");
                                }
                            }
                        }
                    },500);
                }

                @Override
                public void onPoiItemSearched(PoiItemV2 poiItemV2, int i) {

                }
            });
            poiSearchV2.searchPOIAsyn();
        } catch (AMapException e) {
            throw new RuntimeException(e);
        }
    }

    private void initList() {
        ArrayList<MyPoiItem> allDataList = new ArrayList<>();
        for(int i = 0;i < cityResults.size();i++) {
            allDataList.addAll(cityResults.get(i).getResult());
        }
        dataList.clear();
        int totalPage = allDataList.size() / 20;
        if(allDataList.size() % 20 != 0) {
            totalPage++;
        }
        tvTotal.setText("总条数：" + allDataList.size());
        tvTotalPage.setText("总页数：" + totalPage);
        if(pageNum < totalPage) {
            dataList.addAll(allDataList.subList((pageNum - 1) * 20,pageNum * 20));
        }else if(pageNum == totalPage) {
            dataList.addAll(allDataList.subList((pageNum - 1) * 20,allDataList.size()));
        }
        poiAdapter.notifyDataSetChanged();
//        Log.e("当前显示数据",dataList.get(0).getPhotos().get(0).getUrl());
        Log.e("总条目数量",allDataList.size() + "");
    }

//    private void searchPoi() { // 周边搜索
//        AMapLocationClient.updatePrivacyShow(this, true, true);
//        AMapLocationClient.updatePrivacyAgree(this, true);
//        try {
//
//            PoiSearchV2.Query query = new PoiSearchV2.Query(keyword,"",null);
//            query.setPageNum(pageNum);
//            PoiSearchV2.ShowFields ShowFields = new PoiSearchV2.ShowFields(PoiSearchV2.ShowFields.BUSINESS|PoiSearchV2.ShowFields.PHOTOS);
//            query.setShowFields(ShowFields);
//            PoiSearchV2 poiSearchV2 = new PoiSearchV2(this,query);
//            poiSearchV2.setBound(new PoiSearchV2.SearchBound(new LatLonPoint(lat,lng), 10000));//设置周边搜索的中心点以及半径
//
//            PoiSearchResult poiSearchResult = getLocalData(query);
//            if(null != poiSearchResult) {
//                Log.e("123","查询到本地存在相同数据");
//                initList(poiSearchResult.getResultObject());
//            } else {
//                poiSearchV2.setOnPoiSearchListener(new PoiSearchV2.OnPoiSearchListener() {
//                    @Override
//                    public void onPoiSearched(PoiResultV2 poiResultV2, int i) {
//                        initList(poiResultV2);
//                        saveLocalData(query,poiResultV2);
//                    }
//
//                    @Override
//                    public void onPoiItemSearched(PoiItemV2 poiItemV2, int i) {
//
//                    }
//                });
//                poiSearchV2.searchPOIAsyn();
//            }
//        } catch (AMapException e) {
//            throw new RuntimeException(e);
//        }
//    }

}